package controllers

import (
	"beego_background_framework/models"
	"beego_background_framework/utils"
)

// DepartmentControllerController operations for DepartmentController
type DepartmentController struct {
	BaseController
}

func (c *DepartmentController) Index() {
	//组装参数
	pageNo, _ := c.GetInt("page", 1)
	pageSize := c.GetDefaultPageSize()
	name := c.GetString("name", "")
	query := map[string]string{}
	var fields []string
	sort := []string{"sort"}
	order := []string{"desc"}
	offset := (pageNo - 1) * pageSize
	if len(name) != 0 {
		query = map[string]string{"name": name}
	}

	//获取数据
	department, _ := models.GetAllDepartment(query, fields, sort, order, int64(offset), int64(pageSize))

	//管理员总数
	cnt := len(department)
	//处理分页
	paginator := utils.PageUtil(int(cnt), pageSize, c.Ctx.Request.RequestURI, department)
	//填充数据
	c.Data["list"] = department
	c.Data["paginator"] = paginator.ToString()
	c.Data["name"] = name

	//展示
	c.SetTpl("department/index.html")
}

/**
 * 添加单位视图
 */
func (c *DepartmentController) Create() {
	list, _ := models.ListDepartment()

	c.Data["list"] = list
	c.SetTpl("department/create.html")
}

//添加单位
func (c *DepartmentController) Store() {
	d := models.Department{}
	if err := c.ParseForm(&d); err != nil {
		c.ApiError("参数错误", err)
	}
	department, err := models.AddDepartment(&d)

	if err == nil {
		c.ApiSuccess("添加成功", &department)
	}
	c.ApiError("添加失败", err)
}

/**
 * 编辑单位视图
 */
func (c *DepartmentController) Edit() {
	id, err := c.GetUint64(":id")
	if err != nil {
		c.ApiError("id有误", nil)
	}

	department, e := models.GetDepartmentById(int64(id))
	list, _ := models.ListDepartment()
	if e != nil {
		c.ApiError("数据错误", e)
	}

	c.Data["list"] = list
	c.Data["department"] = department
	c.SetTpl("department/edit.html")
}

func (c *DepartmentController) Update() {
	id, err := c.GetUint64(":id")
	if err != nil {
		c.ApiError("id有误", nil)
	}
	d := models.Department{Id: int64(id)}
	if err := c.ParseForm(&d); err != nil {
		c.ApiError("参数错误", err)
	}
	err = models.UpdateDepartmentById(&d)
	if err == nil {
		c.ApiSuccess("更新成功", d)
	}
	c.ApiError("更新失败", err)
}

func (c *DepartmentController) Destroy() {
	id, err := c.GetUint64(":id")
	if err != nil {
		c.ApiError("id有误", nil)
	}
	err = models.DeleteDepartment(int64(id))

	if err == nil {
		c.ApiSuccess("删除成功", id)
	}
	c.ApiError("删除失败", err)
}
